package com.netty.server;

import com.netty.handler.HttpChannelHandler;
import com.netty.handler.SocketChannelHandler;
import com.netty.service.ConnectService;
import com.netty.service.MessageService;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;

/**
 * @author suzhen
 * @create 2018/7/12
 */
@Slf4j
public class ImWebSocketServer {
    private int port;
    /**
     * 负责网络连接接收，处理客户端conn
     */
    private final EventLoopGroup bossGroup = new NioEventLoopGroup();
    /**
     * 负责实际业务处理，就是读写
     */
    private final EventLoopGroup workerGroup = new NioEventLoopGroup();
    private Channel channel;

    @Resource
    private MessageService messageService;

    @Resource
    private ConnectService connectService;

    public void setPort(int port) {
        this.port = port;
    }

    private void start() throws Exception {

        //辅助启动类，tomcat也有这样的启动类
        //启动方式复杂，参数构成是变化的
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                // 创建一个服务管道类型，工厂模式，建立实例
                .channel(NioServerSocketChannel.class)
                //添加日志，是tcp底层，套接字节1024
                .option(ChannelOption.SO_BACKLOG, 1024)
                //绑定调度处理类
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) {
                        //在管道后面添加实际的业务处理类
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new SocketChannelHandler(messageService, connectService));
                    }
                })
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true);

        // 可选参数
        b.childOption(ChannelOption.TCP_NODELAY, true);
        // Bind and start to accept incoming connections.
        // 异步结果监听 Future 用于异步的操作调用，不会阻塞
        ChannelFuture f = b.bind(port).sync();
        channel = f.channel();
        f.addListener((ChannelFutureListener) future -> {
            if (future.isSuccess()) {
                log.info("websocketserver have success bind to {}", port);
            } else {
                log.error("websocketserver fail bind to {}", port);
            }
        });
        //要注释，这是表示一直等待数据
        //channel.closeFuture().sync();

    }

    public void destroy() {
        log.info("destroy qiqiim server ...");
        // 释放线程池资源
        if (channel != null) {
            channel.close();
        }
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
        log.info("destroy qiqiim server complate.");
    }
}
